﻿using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.BO.DHQG;
using DHQGHN.DAL.Common;
using DHQGHN.DAL.Models.DHQG;
using DHQGHN.PM2.Models;
using DHQGHN.PM2.Models.DHQG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DHQGHN.PM2.Controllers
{
    public class ChiTieuController : BaseController
    {
        private ChiTieuBO _sqlChiTieuBO;
        private ChiTieuBO GetSqlChiTieuBO()
        {
            ChiTieuBO sqlBO = new ChiTieuBO();
            return sqlBO;
        }
        public ActionResult Index(ChiTieuModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = "")
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            string strInputMenuUrl = "/ChiTieu/Index";
            List<DHQGHN.PM2.Models.MenuModel> listMenu = Session["MenuList"] as List<DHQGHN.PM2.Models.MenuModel>;
            if (listMenu != null)
            {
                for (int i = 0; i < listMenu.Count; i++)
                {
                    if (listMenu[i].MenuUrl.ToUpper().Equals(strInputMenuUrl.ToUpper()))
                    {
                        ViewBag.ActiveMenus[listMenu[i].ParentMenuId] = "active";
                        ViewBag.ActiveMenus[listMenu[i].MenuId] = "active";
                        ViewBag.CurrentMenuName = listMenu[i].MenuName;
                        ViewBag.Title = listMenu[i].MenuName;
                    }
                }
            }

            var model = Search(a, pageIndex, curentID, false);
            return View(model);
        }

        [HttpPost]
        public ActionResult CreatePopupUpdate(string id)
        {
            _sqlChiTieuBO = GetSqlChiTieuBO();

            ChiTieuModel model = null;
            List<SelectListItem> chiTieuCap1 = new List<SelectListItem>(){
               new SelectListItem(){
                   Text = "--- Chọn chỉ tiêu cấp 1 ---",
                   Value = string.Empty
               }
            };

            List<SelectListItem> chiTieuCap2 = new List<SelectListItem>(){
                new SelectListItem(){
                    Text = "--- Chọn chỉ tiêu cấp 2 ---",
                    Value = string.Empty
                }
            };
            bool isUpdate = false;
            if (!String.IsNullOrEmpty(id) || !String.IsNullOrWhiteSpace(id))
            {
                int chiTieuId = 0;
                if (int.TryParse(id, out chiTieuId))
                {
                    model = new ChiTieuModel(_sqlChiTieuBO.GetById(chiTieuId));
                }
                List<ChiTieuModel> danhSachChiTieuCap1Model = null;
                isUpdate = true;
                if (model != null)
                {
                    if (model.Cap == 2)
                    {
                        danhSachChiTieuCap1Model = GetChiTieuByCap(1);
                        foreach (var chiTieu in danhSachChiTieuCap1Model)
                        {
                            chiTieuCap1.Add(new SelectListItem()
                            {
                                Text = chiTieu.TenChiTieu,
                                Value = chiTieu.MaCap1
                            });
                        }
                    }
                    else if (model.Cap == 3)
                    {
                        danhSachChiTieuCap1Model = GetChiTieuByCap(1);
                        foreach (var chiTieu in danhSachChiTieuCap1Model)
                        {
                            chiTieuCap1.Add(new SelectListItem()
                            {
                                Text = chiTieu.TenChiTieu,
                                Value = chiTieu.MaCap1
                            });
                        }

                        List<ChiTieuModel> danhSachChiTieuCap2Model = GetChiTieuByMaCap1AndCap(model.MaCap1, 2);
                        foreach (var chiTieu in danhSachChiTieuCap2Model)
                        {
                            chiTieuCap2.Add(new SelectListItem()
                            {
                                Text = chiTieu.TenChiTieu,
                                Value = chiTieu.MaCap2
                            });
                        }
                    }
                    else
                    {

                    }
                }
            }

            if (model == null)
            {
                model = new ChiTieuModel();
            }

            ViewBag.DanhSachChiTieuCap1 = chiTieuCap1;
            ViewBag.DanhSachChiTieuCap2 = chiTieuCap2;
            ViewBag.IsUpdate = isUpdate;
            if (Request.IsAjaxRequest())
            {
                return PartialView(model);
            }
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionSave(ChiTieuModel model)
        {
            if (Request.IsAjaxRequest())
            {
                if (!ModelState.IsValid)
                {
                    return Json(JsonResponse.Json200("Dữ liệu không hợp lệ!"));
                }
                string messageLog = string.Empty;
                if (model.ChiTieuId == 0) // cap nhat
                {
                    messageLog = "Thêm mới chỉ tiêu";
                    _sqlChiTieuBO = GetSqlChiTieuBO();
                    if (model.Cap == 1)
                    {
                        long code1 = _sqlChiTieuBO.GetMaxMaCap1();
                        model.TenChiTieuCap1 = model.TenChiTieu;
                        model.TenChiTieuCap2 = string.Empty;
                        model.TenChiTieuCap3 = string.Empty;
                        model.MaCap1 = code1 == 0 ? "10" : (code1 + 1).ToString();
                        model.MaCap2 = string.Empty;
                        model.MaCap3 = string.Empty;
                    }
                    else if (model.Cap == 2)
                    {
                        long code2 = _sqlChiTieuBO.GetMaxMaCap2();
                        model.MaCap2 = code2 == 0 ? "100" : (code2 + 1).ToString();
                        model.TenChiTieuCap2 = model.TenChiTieu;
                        model.TenChiTieuCap3 = string.Empty;
                        model.MaCap3 = string.Empty;
                    }
                    else
                    {
                        long code3 = _sqlChiTieuBO.GetMaxMaCap3();
                        model.MaCap3 = code3 == 0 ? "1000" : (code3 + 1).ToString();
                        model.TenChiTieuCap3 = model.TenChiTieu;
                    }
                    model.Ma = model.MaCap1 + model.MaCap2 + model.MaCap3;
                }
                else
                {
                    messageLog = "Cập nhật chỉ tiêu";
                    if (model.Cap == 1)
                    {
                        model.TenChiTieuCap1 = model.TenChiTieu;
                        model.TenChiTieuCap2 = string.Empty;
                        model.TenChiTieuCap3 = string.Empty;
                    }
                    else if (model.Cap == 2)
                    {
                        model.TenChiTieuCap2 = model.TenChiTieu;
                        model.TenChiTieuCap3 = string.Empty;
                    }
                    else 
                    {
                        model.TenChiTieuCap3 = model.TenChiTieu;
                    }
                    //model.Ma = model.MaCap1 + (model.MaCap2 ?? string.Empty) + (model.MaCap3 ?? string.Empty);
                }
                model.DonViId = GetDonViId();
                model.Type = 1;
                if (IsDonVi())
                {
                    model.Type = 2;
                }
                if (_sqlChiTieuBO == null)
                {
                    _sqlChiTieuBO = GetSqlChiTieuBO();   
                }
                
                bool result = _sqlChiTieuBO.Save(model.ToDALModel());
                if (result)
                {
                    bool logResult = LogStream.Write<ChiTieuModel>(GetAccountLogin(), "Phần mềm nghiệp vụ",
                        "Quản lý chỉ tiêu - ChiTieuController", messageLog + " - ActionSave", model, Helper.KH_DHQGHN_CODE);
                    if (model.ChiTieuId > 0)
                    {
                        return Json(JsonResponse.Json200("Cập nhật thành công!"));
                    }
                    else
                    {
                        string message = "Thêm mới thành công!";
                        return Json(JsonResponse.Json200(message));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult ActionDelete(int id)
        {
            if (Request.IsAjaxRequest())
            {
                _sqlChiTieuBO = GetSqlChiTieuBO();
                bool result = _sqlChiTieuBO.Delete(id);
                if (result)
                {
                    ChiTieuModel model = new ChiTieuModel();
                    model.ChiTieuId = id;

                    LogStream.Write<ChiTieuModel>(GetAccountLogin(),CommonData.AppName,
                        "Quản lý chỉ tiêu - ChiTieuController", "Xóa chỉ tiêu - ActionSave", model, Helper.KH_DHQGHN_CODE);

                    return Json(JsonResponse.Json200("Xóa thành công"));
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }

            return Json("");
        }

        [HttpPost]
        public ActionResult ActionSearch(ChiTieuModel model = null, int pageIndex = 0, string sort = "CertificationId", string sortDir = "ASC", string currentId = "")
        {
            var dataPaging = Search(model, pageIndex, currentId, false);
            return PartialView("~/Views/ChiTieu/_ChiTieuList.cshtml", dataPaging);
        }

        private DataPage<ChiTieuModel> Search(ChiTieuModel myModel, int pageIndex, string currentId, bool compareEqual)
        {
            _sqlChiTieuBO = GetSqlChiTieuBO();
            myModel.Type = 1;
            myModel.DonViId = 0;
            if (IsDonVi())
            {
                myModel.Type = 2;
                myModel.DonViId = GetDonViId();
            }
            var DALModel = _sqlChiTieuBO.GetListPaging(myModel.ToDALModel(), pageIndex, PageSize);
            var models = new DataPage<ChiTieuModel>();
            var lstItem = DALModel.Data;
            foreach (DHQGHN.DAL.Models.DHQG.ChiTieu nguoiDung in lstItem)
            {
                models.Data.Add(new ChiTieuModel(nguoiDung));
            }

            ChiTieuModel model = null;
            if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
            {
                model = models.Data.Find(user => user.ChiTieuId.Equals(currentId));
                models.CustomData = model;
            }
            else
            {
                models.CustomData = myModel;
            }
            if (models.Data.Count > 0)
            {
                //Tao component phan trang
                var pagNative = new Pagination
                {
                    ActionName = "ActionSearch",
                    ModelName = "ChiTieu",
                    CurrentPage = pageIndex,
                    InputSearchId = "",
                    TagetReLoadId = "",
                };
                pagNative.TotalRows = models.Data[0].RecordCount;
                pagNative.CurrentRow = models.Data.Count;
                ViewBag.Pagination = pagNative;
            }
            return models;
        }

        public JsonResult CheckUserNameExist(string TAI_KHOAN, int NGUOI_DUNG_ID)
        {
            try
            {
                //_sqlBO = GetSqlBO();
                //bool result = _sqlBO.CheckUserNameExist(TAI_KHOAN);
                //if (NGUOI_DUNG_ID > 0 && result)
                //{
                //    return Json(result);
                //}
                //// result: true: chua ton tai, nguoc lai da ton tai
                //return Json(!result);
                throw new NotImplementedException("Duong xem lai");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost]
        public JsonResult GetJsonChiTieuByCap(int cap)
        {
            try
            {
                List<ChiTieuModel> danhSachChiTieuModel = GetChiTieuByCap(cap);
                return Json(danhSachChiTieuModel, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public JsonResult GetJsonChiTieuByMaCap1AndCap(string maCap1, int cap)
        {
            try
            {
                List<ChiTieuModel> danhSachChiTieuModel = GetChiTieuByMaCap1AndCap(maCap1, cap);

                return Json(danhSachChiTieuModel, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<ChiTieuModel> GetChiTieuByMaCap1AndCap(string maCap1, int cap)
        {
            try
            {
                _sqlChiTieuBO = GetSqlChiTieuBO();
                List<ChiTieu> danhSachChiTieu = _sqlChiTieuBO.GetByMaCap1_Cap(cap, maCap1);
                List<ChiTieuModel> danhSachChiTieuModel = new List<ChiTieuModel>();
                ChiTieuModel model = null;
                foreach (ChiTieu c in danhSachChiTieu)
                {
                    model = new ChiTieuModel(c);
                    danhSachChiTieuModel.Add(model);
                }

                return danhSachChiTieuModel;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private List<ChiTieuModel> GetChiTieuByCap(int cap)
        {
            try
            {
                _sqlChiTieuBO = GetSqlChiTieuBO();
                List<ChiTieu> danhSachChiTieu = _sqlChiTieuBO.GetByCap(cap);
                List<ChiTieuModel> danhSachChiTieuModel = new List<ChiTieuModel>();
                ChiTieuModel model = null;
                foreach (ChiTieu c in danhSachChiTieu)
                {
                    model = new ChiTieuModel(c);
                    danhSachChiTieuModel.Add(model);
                }

                return danhSachChiTieuModel;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private NguoiDungAdminBO GetSqlBO()
        {
            return new NguoiDungAdminBO();

        }

        private int GetDonViId()
        {
            int donViId = 0;
            if (Session["NguoiDungInfo"] != null)
            {
                NguoiDungModel userInfo = (NguoiDungModel)Session["NguoiDungInfo"];
                List<DHQGHN.PM2.Models.DonViModel> listDonVi = userInfo.listDonVi;
                if (listDonVi != null)
                {
                    donViId = listDonVi.Count > 0 ? listDonVi[0].DonViId : 0;
                }
            }

            return donViId;
        }

        private bool IsDonVi()
        {
            int donViId = 0;
            if (Session["NguoiDungInfo"] != null)
            {
                NguoiDungModel userInfo = (NguoiDungModel)Session["NguoiDungInfo"];
                List<DHQGHN.PM2.Models.DonViModel> listDonVi = userInfo.listDonVi;
                if (listDonVi != null)
                {
                    donViId = listDonVi.Count > 0 ? listDonVi[0].IntCoQuyenGiamSat : -1;
                }
            }

            return donViId == 0 ? true : false;
        }
        private void storebackup()
        {
            //USE [HTTTKH_DHQG]
            //GO
            ///****** Object:  StoredProcedure [dbo].[spChiTieu_GetByMaCap1_Cap]    Script Date: 6/3/2016 11:30:54 PM ******/
            //SET ANSI_NULLS ON
            //GO
            //SET QUOTED_IDENTIFIER ON
            //GO
            //-- =============================================
            //-- Author:		vanduong
            //-- Create date: 20160402
            //-- Description:	<Description,,>
            //-- =============================================
            //alter PROCEDURE [dbo].[spChiTieu_GetMax_MaCap1]	
            //AS
            //BEGIN
            //    DECLARE @Ma varchar(10)
            //    SELECT @Ma = max(MA_CAP1) FROM [DM].[CHITIEU]
            //    SELECT 
            //        COALESCE(Convert(float,(
            //          CASE
            //            WHEN IsNumeric(@Ma) = 1  THEN CAST(@Ma AS float) 
            //            ELSE 0
            //          END
            //        )),0)	
            //END
        }

    }
}